package com.study.recorderbutton.view;

import java.io.File;
import java.util.UUID;

import android.media.MediaRecorder;

public class AudioManager {
	private MediaRecorder mMediaRecorder;
	private String mDir;
	private String mCurrentFilePath;
	
	private static AudioManager mInstance;
	
	private boolean isPrepared;
	
	private AudioManager(String dir){
		mDir = dir;
	}
	
	/**
	 * 回调准备完毕
	 * @author Administrator
	 *
	 */
	public interface AudioStateListener{
		void wellPrepared();
	}
	
	public AudioStateListener mListener;
	
	/**
	 * 供外部类调用的设置回调方法
	 * @param listener
	 */
	public void setOnAudioStateListener(AudioStateListener listener){
		mListener = listener;
	}
	
	/**
	 * 对外公布获取实例的方法
	 * @param dir
	 * @return
	 */
	public static AudioManager getInstance(String dir){
		if(mInstance == null){
			synchronized (AudioManager.class) {
				if(mInstance == null){
					mInstance = new AudioManager(dir);
				}
			}
		}
		return mInstance;
	}
	
	/**
	 * 录音准备工作
	 */
	public void prepareAudio(){
		try {
			isPrepared = false;
			
			File dir = new File(mDir);
			if(!dir.exists()){ //如果文件不存在，则创建文件
				dir.mkdirs();
			}
			
			String fileName = generateFileName();
			File file = new File(dir, fileName);
			
			mCurrentFilePath = file.getAbsolutePath();
			mMediaRecorder = new MediaRecorder();
			//设置输出文件
			mMediaRecorder.setOutputFile(file.getAbsolutePath());
			//设置MediaRecorder的音频源为麦克风
			mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			//设置音频格式
			mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
			//设置音频的编码为amr
			mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
			//准备录音
			mMediaRecorder.prepare();
			//开始，必须在prepare()之后
			mMediaRecorder.start();
			//准备结束
			isPrepared = true;
			
			if(mListener != null){
				mListener.wellPrepared();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 随机生成文件的名称
	 * @return
	 */
	private String generateFileName() {
		return UUID.randomUUID().toString()+".amr";
	}

	/**
	 * 获取声音音量
	 * @param maxLevel
	 * @return
	 */
	public int getVoiceLevel(int maxLevel){
		if(isPrepared && mMediaRecorder != null){
			try {
				//mMediaRecorder.getMaxAmplitude()的返回值在 1~32767 之间
				return maxLevel * mMediaRecorder.getMaxAmplitude()/32768+1; //返回结果1~7
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return 1;
	}
	
	/**
	 * 释放资源
	 */
	public void release(){
		mMediaRecorder.stop();
		mMediaRecorder.release();
		mMediaRecorder = null;
	}
	
	/**
	 * 取消录音
	 */
	public void cancel(){
		release();
		if(mCurrentFilePath != null){
			File file = new File(mCurrentFilePath);
			file.delete(); //取消录音后删除对应文件
			mCurrentFilePath = null;
		}
	}

	/**
	 * 获取当前文件路径
	 * @return
	 */
	public String getCurrentFilePath() {
		return mCurrentFilePath;
	}

}
